package com.gxy.learn.securityauth.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gxy.learn.securityauth.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Description(JWTTOKEN工具类)
 * author: Gao xueyong
 * Create at: 2021/12/1 下午9:24
 */
@Slf4j
public class JwtUtil {

    /**
     * 登录版本号 默认为 1
     */
    public static final String CLAIM_KEY_LOGIN_VERSION = "login_version";
    public static final Integer CLAIM_KEY_LOGIN_VERSION_VAL = 1;
    /**
     * 详看根目录的ehcache.xml
     */
    public static final String CAPTCHA_CACHE_KEY = "tokenVerifyVersion";

    /**
     * 密钥长度，DH算法的默认密钥长度是1024
     * 密钥长度必须是64的倍数，在512到65536位之间
     */
    private static final int KEY_SIZE = 1024;

    protected RSAPublicKey getPublicKey() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(JwtProperties.getSecret());
        } catch (NoSuchAlgorithmException e) {
            log.error("初始化KeyPairGenerator失败！", e);
        }
        keyPairGen.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 公钥
        return (RSAPublicKey) keyPair.getPublic();
    }

    protected RSAPrivateKey getPrivateKey() {
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(JwtProperties.getSecret());
        } catch (NoSuchAlgorithmException e) {
            log.error("初始化KeyPairGenerator失败！", e);
        }
        keyPairGen.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 私钥
        return (RSAPrivateKey) keyPair.getPrivate();
    }


    /**
     * 生成加密token
     *
     * @param userName 用户名
     * @return 加密的token
     */
    public static String sign(String userId, String userName, Integer tokenVersion) {
        Date date = new Date(System.currentTimeMillis() + JwtProperties.getTimeout());
        Algorithm algorithm = Algorithm.HMAC256(JwtProperties.getSecret());
        Map<String, Object> claimMap = new HashMap<>();
        claimMap.put("userId", userId);

        // 附带username信息
        return JWT.create()
                .withJWTId(userId)
                .withSubject(userName)
                .withClaim(loginVersionKey(userName), null == tokenVersion ? CLAIM_KEY_LOGIN_VERSION_VAL : tokenVersion)
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token 秘钥
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(JwtProperties.getSecret());
            com.auth0.jwt.JWTVerifier verifier = JWT.require(algorithm).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            log.info(jwt + ":-token is valid");
            return true;
        } catch (Exception e) {
            log.error("The token is invalid {}", e.getMessage());
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的签发时间
     */
    public static Date getIssuedAt(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getIssuedAt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(String token) {
        Date now = Calendar.getInstance().getTime();
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().before(now);
    }

    /**
     * 获取登录版本号
     *
     * @param token
     * @return
     */
    public static Integer getLoginVersion(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(loginVersionKey(getUsername(token))).asInt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取登录版本号
     *
     * @param userName
     * @return
     */
    public static String loginVersionKey(String userName) {
        return String.format("%s-%s", userName, CLAIM_KEY_LOGIN_VERSION);
    }

//
//    public Map<String, Object> analysisTokenMap(String token) {
//        Map<String, Object> clainmInfoMap = null;
//        try {
//            Algorithm algorithm = Algorithm.RSA256(getPublicKey(), getPrivateKey());
//            JWTVerifier verifier = JWT.require(algorithm)
////                    .withJWTId(userId)//签发id
//                    .withSubject(SUBJECT)//主题
////                    .withIssuer(userName)//签发者
//                    .build(); //Reusable verifier instance
//            DecodedJWT jwt = verifier.verify(token);
//            //自定义字段的获取
//            Claim clainmInfo = jwt.getClaim("clainmInfo");
//            clainmInfoMap = clainmInfo.asMap();
//            log.info("clainmInfo = {}", JSONObject.toJSONString(clainmInfoMap));
//            String header = jwt.getHeader();
//            log.info("header = {}", header);
//            String payload = jwt.getPayload();
//            log.info("payload = {}", payload);
//            String signature = jwt.getSignature();
//            log.info("signature = {}", signature);
//            String issuer = jwt.getIssuer();
//            log.info("issuer = {}", issuer);
//        } catch (JWTVerificationException exception) {
//            //Invalid signature/claims
//            log.error("解析token失败！", exception);
//        }
//        return clainmInfoMap;
//    }
}
